const userInput = document.getElementById('userInput');
const sendButton = document.getElementById('sendButton');
const clearButton = document.getElementById('clearButton');
const chatMessages = document.getElementById('chatMessages');

userInput.addEventListener('input', () => sendButton.disabled = userInput.value.trim() === '');
sendButton.addEventListener('click', sendMessage);
clearButton.addEventListener('click', clearChat);
userInput.addEventListener('keydown', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); if (!sendButton.disabled) sendMessage(); }
});

// （保留你已有的 marked/hljs 配置）
// ... marked/hljs 配置不变 ...

function sendMessage() {
    const message = userInput.value.trim();
    if (!message) return;
    userInput.value = '';
    sendButton.disabled = true;

    // 添加用户消息
    addMessage(message, 'user');

    // 重写：不立即创建 AI 气泡；插入独立的“思考中”指示器，直到内容真正到达
    const typingEl = addTypingIndicatorTo(chatMessages);
    let typingRemoved = false;
    let fullText = '';
    let createdAnyOutput = false;
    let aiContainer = null;
    let contentDiv = null;

    fetch('/api/chat/stream', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ messages: [{ role: 'user', content: message }], stream: true })
    })
    .then(async resp => {
        if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
        if (!resp.body) throw new Error('无响应体');

        const reader = resp.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';
        scrollToBottom();
        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            buffer += decoder.decode(value, { stream: true });

            // 处理完整的 SSE 事件
            let eventEndIdx;
            while ((eventEndIdx = buffer.indexOf('\n\n')) !== -1) {
                const event = buffer.slice(0, eventEndIdx);
                buffer = buffer.slice(eventEndIdx + 2);
                const lines = event.split('\n').map(l => l.trim()).filter(Boolean);
                for (const line of lines) {
                    const dataPrefix = line.startsWith('data:') ? line.substring(5).trim() : line;
                    if (dataPrefix === '[DONE]') {
                        // 仅当已有输出时才移除“思考中”并完成渲染
                        if (createdAnyOutput) {
                            if (!typingRemoved) { typingEl.remove(); typingRemoved = true; }
                            finalRender(fullText, contentDiv);
                        }
                        sendButton.disabled = false;
                        return;
                    }
                    // 解析 JSON 或作为纯文本追加
                    try {
                        const parsed = JSON.parse(dataPrefix);
                        if (parsed.choices && Array.isArray(parsed.choices)) {
                            for (const c of parsed.choices) {
                                const piece = (c.delta && c.delta.content) || c.text || '';
                                if (piece) { fullText += piece; }
                            }
                        } else if (parsed.content || parsed.text) {
                            fullText += (parsed.content || parsed.text);
                        } else {
                            fullText += JSON.stringify(parsed);
                        }
                    } catch {
                        fullText += dataPrefix;
                    }

                    // 首次有实际内容时创建 AI 气泡，并移除“思考中”
                    if (!createdAnyOutput && fullText.trim().length > 0) {
                        createdAnyOutput = true;
                        aiContainer = document.createElement('div');
                        aiContainer.className = 'message ai-message';
                        contentDiv = document.createElement('div');
                        contentDiv.className = 'message-content';
                        aiContainer.appendChild(contentDiv);
                        chatMessages.appendChild(aiContainer);
                        if (!typingRemoved) { typingEl.remove(); typingRemoved = true; }
                    }

                    if (createdAnyOutput) {
                        //contentDiv.textContent = fullText;
                        finalRender(fullText, contentDiv);
                        scrollToBottom();
                    }
                }
            }

            // 处理单行缓冲，避免长时间不显示首片段
            let singleIdx;
            while ((singleIdx = buffer.indexOf('\n')) !== -1) {
                const line = buffer.slice(0, singleIdx).trim();
                buffer = buffer.slice(singleIdx + 1);
                if (!line) continue;
                const dataPrefix = line.startsWith('data:') ? line.substring(5).trim() : line;
                if (dataPrefix === '[DONE]') {
                    if (createdAnyOutput) {
                        if (!typingRemoved) { typingEl.remove(); typingRemoved = true; }
                        finalRender(fullText, contentDiv);
                    }
                    sendButton.disabled = false;
                    return;
                }
                try {
                    const parsed = JSON.parse(dataPrefix);
                    if (parsed.choices && Array.isArray(parsed.choices)) {
                        for (const c of parsed.choices) {
                            const piece = (c.delta && c.delta.content) || c.text || '';
                            if (piece) fullText += piece;
                        }
                    } else if (parsed.content || parsed.text) {
                        fullText += (parsed.content || parsed.text);
                    } else {
                        fullText += JSON.stringify(parsed);
                    }
                } catch {
                    fullText += dataPrefix;
                }

                if (!createdAnyOutput && fullText.trim().length > 0) {
                    createdAnyOutput = true;
                    aiContainer = document.createElement('div');
                    aiContainer.className = 'message ai-message';
                    contentDiv = document.createElement('div');
                    contentDiv.className = 'message-content';
                    aiContainer.appendChild(contentDiv);
                    chatMessages.appendChild(aiContainer);
                    if (!typingRemoved) { typingEl.remove(); typingRemoved = true; }
                }
                if (createdAnyOutput) {
                    //contentDiv.textContent = fullText;
                    finalRender(fullText, contentDiv);
                    scrollToBottom();
                }
            }
        }

        // 流结束但未收到 [DONE]：根据是否有输出决定是否移除“思考中”
        if (createdAnyOutput) {
            if (!typingRemoved) { typingEl.remove(); typingRemoved = true; }
            finalRender(fullText, contentDiv);
        }
        sendButton.disabled = false;
    })
    .catch(err => {
        // 出错时移除“思考中”并给出错误消息
        if (typingEl && typingEl.parentNode) typingEl.remove();
        const errDiv = document.createElement('div');
        errDiv.className = 'message ai-message';
        const c = document.createElement('div'); c.className = 'message-content';
        c.innerHTML = `<span style="color:red;">请求失败: ${escapeHtml(err.message)}</span>`;
        errDiv.appendChild(c);
        chatMessages.appendChild(errDiv);
        scrollToBottom();
    })
    .finally(() => { sendButton.disabled = false; });
}

// 将 typing 指示器插入到指定父节点（不使用 message-content 以避免背景）
function addTypingIndicatorTo(parentNode) {
    const wrapper = document.createElement('div');
    wrapper.className = 'typing-indicator';
    for (let i = 0; i < 3; i++) {
        const dot = document.createElement('span');
        dot.className = 'typing-dot';
        dot.style.animationDelay = `${i * 0.12}s`;
        wrapper.appendChild(dot);
    }
    parentNode.appendChild(wrapper);
    return wrapper;
}

// 替换或添加下面三个函数：debugMarkdownParse / renderMathSafely / finalRender

function debugMarkdownParse(src) {
    try {
        if (window.marked) {
            // 使用 marked 的解析接口，不在此处触发 MathJax
            if (typeof window.marked.parse == 'function') return window.marked.parse(src);
            return window.marked(src);
        }
        return (src || '').replace(/\n/g, '<br>');

    } catch (err) {
        console.error('debugMarkdownParse error', err);
        return null;
    }
}

// 安全触发 MathJax 渲染，针对传入的 DOM 节点
function renderMathSafely(container) {
    try {
        if (window.MathJax && typeof MathJax.typesetPromise == 'function') {
            return MathJax.typesetPromise([container]).catch(err => console.error('MathJax.typesetPromise 错误:', err));
        }
        if (window.MathJax && typeof MathJax.typeset == 'function') {
            try { MathJax.typeset([container]); } catch (e) { console.error('MathJax.typeset 错误:', e); }
        }
    } catch (e) {
        console.error('renderMathSafely 异常:', e);
    }
    return Promise.resolve();
}

function finalRender(text, contentDiv) {
    try {
        const src = text || '';
        const parsed = debugMarkdownParse(src);
        if (parsed != null) {
            contentDiv.innerHTML = parsed;
        } else {
            contentDiv.textContent = src;
        }
    } catch (e) {
        contentDiv.textContent = text;
    }
    // 在 DOM 内容写入后再运行 MathJax（必须传入 DOM 节点）
    renderMathSafely(contentDiv).then(() => {
        scrollToBottom();
    });
}

// 其他工具函数保持不变（略写）
function addMessage(content, sender) {
    const container = document.createElement('div'); container.className = `message ${sender}-message`;
    const c = document.createElement('div'); c.className = 'message-content'; c.textContent = content;
    container.appendChild(c); chatMessages.appendChild(container); scrollToBottom();
}
function clearChat() { chatMessages.innerHTML = `<div class="system-message">欢迎使用DeepSeek AI聊天助手！</div>`; }
function scrollToBottom() { chatMessages.scrollTop = chatMessages.scrollHeight; }
//function escapeHtml(s) { return (s+'').replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[m]); }

// 创建自定义渲染器
const renderer = new marked.Renderer();



// 转义html代码(对应字符转移为html实体)，防止在浏览器渲染
function escapeHtml(html) {
    let text = document.createTextNode(html);
    let div = document.createElement('div');
    div.appendChild(text);
    return div.innerHTML;
}